package com.business.user.listener;

import com.alibaba.fastjson.JSONObject;
import com.business.common.enums.RabbitMqConstant;
import com.business.user.service.MessageService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 监听添加消息
 */
@Service
public class MessageListener {
    private Logger logger = LoggerFactory.getLogger(MessageListener.class);

    @Autowired
    private MessageService messageService;

    /**
     * 监听 添加消息队列
     *
     * @param message
     * @param channel
     */
    @RabbitListener(queues = RabbitMqConstant.ADD_MESSAGE)
    public void sendVerificationCodeListener(Message message, Channel channel) throws IOException {
        JSONObject params = JSONObject.parseObject(new String(message.getBody()));
        logger.info(RabbitMqConstant.ADD_MESSAGE + " 接收参数执行开始,参数： " + params);
        if (null == params) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        try {
            com.business.user.entity.Message userMessage = params.toJavaObject(com.business.user.entity.Message.class);
            messageService.add(userMessage);
            logger.info(RabbitMqConstant.ADD_MESSAGE + " 执行结束");
        }  finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
